package logic

import (
	"context"
	"errors"
	"houseRpc/models"
	"houseRpc/pkg"

	"houseRpc/house"
	"houseRpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameAuthLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameAuthLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameAuthLogic {
	return &RealNameAuthLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealNameAuthLogic) RealNameAuth(in *house.RealNameAuthRequest) (*house.RealNameAuthResponse, error) {
	// todo: add your logic here and delete this line
	var err error
	var ur models.RealName
	ur.UserId = in.UserId

	if err = ur.GetRealNameByUserId(); err != nil {
		logx.Error("用户信息获取失败")
		return nil, errors.New("用户信息获取失败")
	}

	if ur.ID != 0 {
		logx.Error("用户已实名")
		return nil, errors.New("用户已实名")
	}

	if !pkg.AuThRealName(in.IdCard, in.RealName) {
		logx.Error("实名失败：调用第三方实名认证接口")
		return nil, errors.New("实名失败")
	}

	ur.RealName = in.RealName
	ur.IdCard = pkg.Md5(in.IdCard)

	if err = ur.CreateRealName(); err != nil {
		logx.Error("用户实名失败")
		return nil, errors.New("用户实名失败")
	}
	return &house.RealNameAuthResponse{}, nil
}
